<!-- @ts-nocheck -->
<template>
  <view class="admin-profile-container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 管理员信息头部 -->
    <view class="profile-header">
      <view class="admin-info">
        <view class="avatar-section" @click="showAvatarOptions">
          <image 
            v-if="adminInfo.avatarUrl" 
            :src="adminInfo.avatarUrl" 
            class="admin-avatar"
            mode="aspectFill"
          />
          <view v-else class="default-avatar">
            <text class="avatar-text">{{ getAvatarText() }}</text>
          </view>
          <view class="camera-icon">
            <uni-icons type="camera" size="16" color="#fff"></uni-icons>
          </view>
        </view>
        <view class="admin-details">
          <text class="admin-name">{{ adminInfo.username || '管理员' }}</text>
          <text class="admin-role">{{ getRoleName() }}</text>
        </view>
      </view>
      
      <!-- 统计信息 -->
      <view class="stats-section">
        <view class="stat-item">
          <text class="stat-number">{{ adminStats.totalAdmins }}</text>
          <text class="stat-label">管理员</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ adminStats.activeAdmins }}</text>
          <text class="stat-label">在线</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ adminStats.todayLogins }}</text>
          <text class="stat-label">今日登录</text>
        </view>
      </view>
    </view>

    <!-- 管理功能 -->
    <view class="management-section">
      <view class="section-header">
        <text class="section-title">管理功能</text>
        <view class="view-all" @click="viewAllAdmins">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      
      <view class="function-grid">
        <view class="function-item" @click="showAdminList">
          <view class="function-icon admin-list-icon">
            <uni-icons type="person" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">管理员列表</text>
        </view>
        <view class="function-item" @click="showCreateAdmin">
          <view class="function-icon create-admin-icon">
            <uni-icons type="plus" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">创建管理员</text>
        </view>
        <view class="function-item" @click="showRoleManagement">
          <view class="function-icon role-icon">
            <uni-icons type="gear" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">角色管理</text>
        </view>
        <view class="function-item" @click="showSystemSettings">
          <view class="function-icon settings-icon">
            <uni-icons type="settings" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">系统设置</text>
        </view>
        <view class="function-item" @click="showSecurityCenter">
          <view class="function-icon security-icon">
            <uni-icons type="locked" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">安全中心</text>
        </view>
        <view class="function-item" @click="showOperationLog">
          <view class="function-icon log-icon">
            <uni-icons type="list" size="24" color="#FF8C42"></uni-icons>
          </view>
          <text class="function-text">操作日志</text>
        </view>
      </view>
    </view>

    <!-- 个人设置 -->
    <view class="settings-section">
      <view class="section-header">
        <text class="section-title">个人设置</text>
      </view>
      
      <view class="settings-list">
        <view class="setting-item" @click="editProfile">
          <view class="setting-left">
            <uni-icons type="person" size="20" color="#666"></uni-icons>
            <text class="setting-text">编辑资料</text>
          </view>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
        <view class="setting-item" @click="changePassword">
          <view class="setting-left">
            <uni-icons type="locked" size="20" color="#666"></uni-icons>
            <text class="setting-text">修改密码</text>
          </view>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
        <view class="setting-item" @click="showNotificationSettings">
          <view class="setting-left">
            <uni-icons type="notification" size="20" color="#666"></uni-icons>
            <text class="setting-text">通知设置</text>
          </view>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
        <view class="setting-item" @click="showAbout">
          <view class="setting-left">
            <uni-icons type="info" size="20" color="#666"></uni-icons>
            <text class="setting-text">关于系统</text>
          </view>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-section">
      <view class="logout-btn" @click="logout">
        <text class="logout-text">退出登录</text>
      </view>
    </view>

    <!-- 管理员列表弹窗 -->
    <view v-if="showAdminListModal" class="modal-overlay" @click="closeAdminListModal">
      <view class="admin-list-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">管理员列表</text>
          <view class="modal-close" @click="closeAdminListModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="search-section">
            <input 
              class="search-input" 
              v-model="searchKeyword" 
              placeholder="搜索管理员用户名"
              @input="searchAdmins"
            />
            <view class="status-filter">
              <view 
                class="filter-item" 
                :class="{ 'active': statusFilter === 'all' }"
                @click="setStatusFilter('all')"
              >
                全部
              </view>
              <view 
                class="filter-item" 
                :class="{ 'active': statusFilter === 1 }"
                @click="setStatusFilter(1)"
              >
                启用
              </view>
              <view 
                class="filter-item" 
                :class="{ 'active': statusFilter === 0 }"
                @click="setStatusFilter(0)"
              >
                停用
              </view>
            </view>
          </view>
          <view class="admin-list">
            <view 
              v-for="admin in displayAdminList" 
              :key="admin.id" 
              class="admin-item"
            >
              <view class="admin-item-left">
                <image 
                  v-if="admin.avatarUrl" 
                  :src="admin.avatarUrl" 
                  class="admin-item-avatar"
                />
                <view v-else class="admin-item-default-avatar">
                  <text>{{ admin.username?.charAt(0)?.toUpperCase() || 'A' }}</text>
                </view>
                <view class="admin-item-info">
                  <text class="admin-item-name">{{ admin.username }}</text>
                  <text class="admin-item-time">创建时间: {{ formatDate(admin.createTime) }}</text>
                  <text class="admin-item-update">更新时间: {{ formatDate(admin.updateTime) }}</text>
                </view>
              </view>
              <view class="admin-item-actions">
                <view 
                  class="status-toggle" 
                  :class="{ 'active': admin.status === 1 }"
                  @click="toggleAdminStatus(admin)"
                >
                  <text>{{ admin.status === 1 ? '启用' : '停用' }}</text>
                </view>
                <view class="role-btn" @click="assignRole(admin)">
                  <uni-icons type="gear" size="16" color="#FF8C42"></uni-icons>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 分页控制 -->
          <view v-if="totalPages > 1" class="pagination-controls">
            <view 
              class="page-btn" 
              :class="{ 'disabled': currentPage === 1 }"
              @click="prevPage"
            >
              上一页
            </view>
            <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
            <view 
              class="page-btn" 
              :class="{ 'disabled': currentPage === totalPages }"
              @click="nextPage"
            >
              下一页
            </view>
          </view>
          
          <view v-if="isLoadingAdmins" class="loading-state">
            <uni-icons type="spinner-cycle" size="24" color="#FF8C42"></uni-icons>
            <text>加载中...</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 创建管理员弹窗 -->
    <view v-if="showCreateAdminModal" class="modal-overlay" @click="closeCreateAdminModal">
      <view class="create-admin-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">创建管理员</text>
          <view class="modal-close" @click="closeCreateAdminModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">用户名 *</text>
            <input 
              class="form-input" 
              v-model="newAdmin.username" 
              placeholder="请输入用户名"
            />
          </view>
          <view class="form-item">
            <text class="form-label">密码 *</text>
            <input 
              class="form-input" 
              v-model="newAdmin.password" 
              placeholder="请输入密码"
              type="password"
            />
          </view>
          <view class="form-item">
            <text class="form-label">头像URL</text>
            <input 
              class="form-input" 
              v-model="newAdmin.avatarUrl" 
              placeholder="请输入头像URL（可选）"
            />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <view class="status-selector">
              <view 
                class="status-option" 
                :class="{ 'active': newAdmin.status === 1 }"
                @click="newAdmin.status = 1"
              >
                启用
              </view>
              <view 
                class="status-option" 
                :class="{ 'active': newAdmin.status === 0 }"
                @click="newAdmin.status = 0"
              >
                停用
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeCreateAdminModal">取消</view>
          <view class="confirm-btn" @click="createAdmin">创建</view>
        </view>
      </view>
    </view>

    <!-- 编辑资料弹窗 -->
    <view v-if="showEditProfileModal" class="modal-overlay" @click="closeEditProfileModal">
      <view class="edit-profile-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑资料</text>
          <view class="modal-close" @click="closeEditProfileModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">用户名 *</text>
            <input 
              class="form-input" 
              v-model="editProfileForm.username" 
              placeholder="请输入用户名"
            />
          </view>
          <view class="form-item">
            <text class="form-label">头像URL</text>
            <input 
              class="form-input" 
              v-model="editProfileForm.avatarUrl" 
              placeholder="请输入头像URL（可选）"
            />
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeEditProfileModal">取消</view>
          <view class="confirm-btn" @click="updateProfile">保存</view>
        </view>
      </view>
    </view>

    <!-- 修改密码弹窗 -->
    <view v-if="showPasswordModal" class="modal-overlay" @click="closePasswordModal">
      <view class="password-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">修改密码</text>
          <view class="modal-close" @click="closePasswordModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">当前密码</text>
            <input 
              class="form-input" 
              v-model="passwordForm.oldPassword" 
              placeholder="请输入当前密码"
              type="password"
            />
          </view>
          <view class="form-item">
            <text class="form-label">新密码</text>
            <input 
              class="form-input" 
              v-model="passwordForm.newPassword" 
              placeholder="请输入新密码"
              type="password"
            />
          </view>
          <view class="form-item">
            <text class="form-label">确认新密码</text>
            <input 
              class="form-input" 
              v-model="passwordForm.confirmPassword" 
              placeholder="请再次输入新密码"
              type="password"
            />
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closePasswordModal">取消</view>
          <view class="confirm-btn" @click="updatePassword">确认修改</view>
        </view>
      </view>
    </view>

    <!-- 角色分配弹窗 -->
    <view v-if="showRoleModal" class="modal-overlay" @click="closeRoleModal">
      <view class="role-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">分配角色 - {{ currentAdmin?.username }}</text>
          <view class="modal-close" @click="closeRoleModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="role-list">
            <view 
              v-for="role in availableRoles" 
              :key="role.id"
              class="role-item"
              @click="toggleRole(role.id)"
            >
              <view class="role-checkbox" :class="{ 'checked': selectedRoles.includes(role.id) }">
                <uni-icons v-if="selectedRoles.includes(role.id)" type="checkmarkempty" size="16" color="#FFFFFF"></uni-icons>
              </view>
              <view class="role-info">
                <text class="role-name">{{ role.name }}</text>
                <text class="role-description">{{ role.description }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeRoleModal">取消</view>
          <view class="confirm-btn" @click="saveRoles">保存角色</view>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <tab-bar :active="3"></tab-bar>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'

// 基础数据
const statusBarHeight = ref<number>(0)
const showAdminListModal = ref<boolean>(false)
const showCreateAdminModal = ref<boolean>(false)
const showEditProfileModal = ref<boolean>(false)
const showPasswordModal = ref<boolean>(false)
const showRoleModal = ref<boolean>(false)
const isLoadingAdmins = ref<boolean>(false)
const searchKeyword = ref<string>('')
const statusFilter = ref<string | number>('all')
const currentAdmin = ref<any>(null)
const selectedRoles = ref<number[]>([])

// 分页相关
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const totalPages = ref<number>(1)

// 管理员信息
const adminInfo = reactive({
  id: 2,
  username: 'admin',
  avatarUrl: '/images/avatar/default0',
  status: 1
})

// 管理员统计
const adminStats = reactive({
  totalAdmins: 0,
  activeAdmins: 0,
  todayLogins: 0
})

// 模拟管理员数据 - 密码改为 admin
const mockAdminData = [
  {
    id: 1,
    username: 'superadmin',
    password: 'admin',
    avatarUrl: '/images/avatar/admin1.png',
    status: 1,
    createTime: '2025-05-13 22:38:53',
    updateTime: '2025-05-13 22:38:53'
  },
  {
    id: 2,
    username: 'admin',
    password: 'admin',
    avatarUrl: '/images/avatar/default0',
    status: 1,
    createTime: '2025-05-13 22:38:53',
    updateTime: '2025-05-13 22:38:53'
  },
  {
    id: 3,
    username: 'manager',
    password: 'admin',
    avatarUrl: '',
    status: 1,
    createTime: '2025-05-14 10:20:15',
    updateTime: '2025-05-14 10:20:15'
  },
  {
    id: 4,
    username: 'operator',
    password: 'admin',
    avatarUrl: '',
    status: 0,
    createTime: '2025-05-14 15:30:22',
    updateTime: '2025-05-14 15:30:22'
  },
  {
    id: 5,
    username: 'viewer',
    password: 'admin',
    avatarUrl: '/images/avatar/viewer.png',
    status: 1,
    createTime: '2025-05-15 09:45:10',
    updateTime: '2025-05-15 09:45:10'
  }
]

// 可用角色数据
const availableRoles = ref([
  { id: 1, name: '超级管理员', description: '拥有所有权限' },
  { id: 2, name: '普通管理员', description: '拥有基本管理权限' },
  { id: 3, name: '只读管理员', description: '只能查看数据' }
])

// 管理员列表
const adminList = ref<any[]>([])

// 新管理员表单
const newAdmin = reactive({
  username: '',
  password: '',
  avatarUrl: '',
  status: 1
})

// 编辑资料表单
const editProfileForm = reactive({
  username: '',
  avatarUrl: ''
})

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性 - 显示的管理员列表
const displayAdminList = computed(() => {
  let filteredList = adminList.value

  // 应用搜索过滤
  if (searchKeyword.value) {
    filteredList = filteredList.filter(admin => 
      admin.username.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 应用状态过滤
  if (statusFilter.value !== 'all') {
    filteredList = filteredList.filter(admin => admin.status === statusFilter.value)
  }

  return filteredList
})

// 获取状态栏高度
const getStatusBarHeight = (): void => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight || 0
  } catch (e) {
    console.error('获取系统信息失败:', e)
    statusBarHeight.value = 0
  }
}

// 获取当前管理员信息 - 使用模拟数据
const fetchAdminInfo = async (): Promise<void> => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 使用模拟数据
    const currentAdminData = mockAdminData.find(admin => admin.id === adminInfo.id)
    if (currentAdminData) {
      Object.assign(adminInfo, currentAdminData)
    }
    
    console.log('管理员信息加载完成:', adminInfo)
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    uni.showToast({
      title: '获取信息失败',
      icon: 'none'
    })
  }
}

// 获取管理员列表 - 使用模拟数据
const fetchAdminList = async (page: number = 1): Promise<void> => {
  isLoadingAdmins.value = true
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用模拟数据
    let filteredData = [...mockAdminData]
    
    // 应用搜索过滤
    if (searchKeyword.value) {
      filteredData = filteredData.filter(admin => 
        admin.username.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    }
    
    // 应用状态过滤
    if (statusFilter.value !== 'all') {
      filteredData = filteredData.filter(admin => admin.status === statusFilter.value)
    }
    
    // 计算分页
    const total = filteredData.length
    totalPages.value = Math.ceil(total / pageSize.value)
    
    const startIndex = (page - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    adminList.value = filteredData.slice(startIndex, endIndex)
    
    // 更新统计信息
    updateAdminStats()
    
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    uni.showToast({
      title: '获取列表失败',
      icon: 'none'
    })
  } finally {
    isLoadingAdmins.value = false
  }
}

// 更新管理员统计
const updateAdminStats = (): void => {
  adminStats.totalAdmins = mockAdminData.length
  adminStats.activeAdmins = mockAdminData.filter(admin => admin.status === 1).length
  adminStats.todayLogins = Math.floor(Math.random() * 10) + 1 // 模拟今日登录数
}

// 创建管理员 - 使用模拟数据
const createAdmin = async (): Promise<void> => {
  if (!newAdmin.username || !newAdmin.password) {
    uni.showToast({
      title: '请填写用户名和密码',
      icon: 'none'
    })
    return
  }
  
  // 检查用户名是否已存在
  const existingAdmin = mockAdminData.find(admin => admin.username === newAdmin.username)
  if (existingAdmin) {
    uni.showToast({
      title: '用户名已存在',
      icon: 'none'
    })
    return
  }
  
  uni.showLoading({ title: '创建中...' })
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 创建新管理员
    const newId = Math.max(...mockAdminData.map(admin => admin.id)) + 1
    const now = new Date().toISOString().replace('T', ' ').substring(0, 19)
    
    const newAdminData = {
      id: newId,
      username: newAdmin.username,
      password: newAdmin.password, // 直接使用明文密码
      avatarUrl: newAdmin.avatarUrl || '',
      status: newAdmin.status,
      createTime: now,
      updateTime: now
    }
    
    // 添加到模拟数据
    mockAdminData.push(newAdminData)
    
    uni.showToast({
      title: '创建成功',
      icon: 'success'
    })
    
    closeCreateAdminModal()
    resetNewAdminForm()
    fetchAdminList(currentPage.value)
    
  } catch (error) {
    console.error('创建管理员失败:', error)
    uni.showToast({
      title: '创建失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 更新个人资料 - 使用模拟数据
const updateProfile = async (): Promise<void> => {
  if (!editProfileForm.username) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none'
    })
    return
  }
  
  // 检查用户名是否已被其他管理员使用
  const existingAdmin = mockAdminData.find(admin => 
    admin.username === editProfileForm.username && admin.id !== adminInfo.id
  )
  if (existingAdmin) {
    uni.showToast({
      title: '用户名已被使用',
      icon: 'none'
    })
    return
  }
  
  uni.showLoading({ title: '更新中...' })
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 更新模拟数据
    const adminIndex = mockAdminData.findIndex(admin => admin.id === adminInfo.id)
    if (adminIndex !== -1) {
      mockAdminData[adminIndex].username = editProfileForm.username
      mockAdminData[adminIndex].avatarUrl = editProfileForm.avatarUrl
      mockAdminData[adminIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    }
    
    // 更新当前管理员信息
    adminInfo.username = editProfileForm.username
    adminInfo.avatarUrl = editProfileForm.avatarUrl
    
    uni.showToast({
      title: '资料更新成功',
      icon: 'success'
    })
    
    closeEditProfileModal()
    
  } catch (error) {
    console.error('更新资料失败:', error)
    uni.showToast({
      title: '更新失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 切换管理员状态 - 使用模拟数据
const toggleAdminStatus = async (admin: any): Promise<void> => {
  const newStatus = admin.status === 1 ? 0 : 1
  
  uni.showModal({
    title: '确认操作',
    content: `确定要${newStatus === 1 ? '启用' : '停用'}管理员"${admin.username}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        uni.showLoading({ title: '处理中...' })
        
        try {
          // 模拟API调用延迟
          await new Promise(resolve => setTimeout(resolve, 800))
          
          // 更新模拟数据
          const adminIndex = mockAdminData.findIndex(a => a.id === admin.id)
          if (adminIndex !== -1) {
            mockAdminData[adminIndex].status = newStatus
            mockAdminData[adminIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
          }
          
          // 更新本地数据
          admin.status = newStatus
          
          // 更新统计
          updateAdminStats()
          
          uni.showToast({
            title: newStatus === 1 ? '已启用' : '已停用',
            icon: 'success'
          })
          
        } catch (error) {
          console.error('更新状态失败:', error)
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 分配角色 - 使用模拟数据
const assignRole = async (admin: any): Promise<void> => {
  currentAdmin.value = admin
  
  // 模拟获取当前管理员的角色
  selectedRoles.value = [2] // 默认分配普通管理员角色
  showRoleModal.value = true
}

// 切换角色选择
const toggleRole = (roleId: number): void => {
  const index = selectedRoles.value.indexOf(roleId)
  if (index > -1) {
    selectedRoles.value.splice(index, 1)
  } else {
    selectedRoles.value.push(roleId)
  }
}

// 保存角色分配 - 使用模拟数据
const saveRoles = async (): Promise<void> => {
  if (!currentAdmin.value) return
  
  uni.showLoading({ title: '保存中...' })
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 这里可以保存角色分配到本地存储或其他地方
    console.log(`为管理员 ${currentAdmin.value.username} 分配角色:`, selectedRoles.value)
    
    uni.showToast({
      title: '角色分配成功',
      icon: 'success'
    })
    
    closeRoleModal()
    
  } catch (error) {
    console.error('分配角色失败:', error)
    uni.showToast({
      title: '角色分配失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 更新密码 - 使用模拟数据
const updatePassword = async (): Promise<void> => {
  if (!passwordForm.oldPassword || !passwordForm.newPassword) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    })
    return
  }
  
  // 验证旧密码
  if (passwordForm.oldPassword !== 'admin') {
    uni.showToast({
      title: '当前密码错误',
      icon: 'none'
    })
    return
  }
  
  uni.showLoading({ title: '修改中...' })
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新模拟数据中的密码
    const adminIndex = mockAdminData.findIndex(admin => admin.id === adminInfo.id)
    if (adminIndex !== -1) {
      mockAdminData[adminIndex].password = passwordForm.newPassword
      mockAdminData[adminIndex].updateTime = new Date().toISOString().replace('T', ' ').substring(0, 19)
    }
    
    uni.showToast({
      title: '密码修改成功',
      icon: 'success'
    })
    
    closePasswordModal()
    resetPasswordForm()
    
  } catch (error) {
    console.error('修改密码失败:', error)
    uni.showToast({
      title: '密码修改失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 工具函数
const getAvatarText = (): string => {
  return adminInfo.username?.charAt(0)?.toUpperCase() || 'A'
}

const getRoleName = (): string => {
  return '超级管理员' // 模拟角色名称
}

const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const resetNewAdminForm = (): void => {
  newAdmin.username = ''
  newAdmin.password = ''
  newAdmin.avatarUrl = ''
  newAdmin.status = 1
}

const resetEditProfileForm = (): void => {
  editProfileForm.username = ''
  editProfileForm.avatarUrl = ''
}

const resetPasswordForm = (): void => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 事件处理函数
const showAvatarOptions = (): void => {
  uni.showActionSheet({
    itemList: ['拍照', '从相册选择'],
    success: (res) => {
      const sourceType = res.tapIndex === 0 ? ['camera'] : ['album']
      uni.chooseImage({
        count: 1,
        sourceType,
        success: (res) => {
          // 模拟上传头像
          console.log('选择的图片:', res.tempFilePaths[0])
          adminInfo.avatarUrl = res.tempFilePaths[0]
          uni.showToast({
            title: '头像更新成功',
            icon: 'success'
          })
        }
      })
    }
  })
}

const showAdminList = (): void => {
  showAdminListModal.value = true
  currentPage.value = 1
  fetchAdminList(1)
}

const closeAdminListModal = (): void => {
  showAdminListModal.value = false
  searchKeyword.value = ''
  statusFilter.value = 'all'
}

const showCreateAdmin = (): void => {
  showCreateAdminModal.value = true
}

const closeCreateAdminModal = (): void => {
  showCreateAdminModal.value = false
  resetNewAdminForm()
}

const editProfile = (): void => {
  // 初始化编辑表单
  editProfileForm.username = adminInfo.username
  editProfileForm.avatarUrl = adminInfo.avatarUrl
  showEditProfileModal.value = true
}

const closeEditProfileModal = (): void => {
  showEditProfileModal.value = false
  resetEditProfileForm()
}

const changePassword = (): void => {
  showPasswordModal.value = true
}

const closePasswordModal = (): void => {
  showPasswordModal.value = false
  resetPasswordForm()
}

const closeRoleModal = (): void => {
  showRoleModal.value = false
  currentAdmin.value = null
  selectedRoles.value = []
}

const searchAdmins = (): void => {
  currentPage.value = 1
  fetchAdminList(1)
}

const setStatusFilter = (status: string | number): void => {
  statusFilter.value = status
  currentPage.value = 1
  fetchAdminList(1)
}

const prevPage = (): void => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchAdminList(currentPage.value)
  }
}

const nextPage = (): void => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchAdminList(currentPage.value)
  }
}

const viewAllAdmins = (): void => {
  showAdminList()
}

const showRoleManagement = (): void => {
  uni.navigateTo({
    url: '/pages/useers/users'
  })
}

const showSystemSettings = (): void => {
  uni.showToast({
    title: '系统设置功能开发中',
    icon: 'none'
  })
}

const showSecurityCenter = (): void => {
  uni.showToast({
    title: '安全中心功能开发中',
    icon: 'none'
  })
}

const showOperationLog = (): void => {
  uni.showToast({
    title: '操作日志功能开发中',
    icon: 'none'
  })
}

const showNotificationSettings = (): void => {
  uni.showToast({
    title: '通知设置功能开发中',
    icon: 'none'
  })
}

const showAbout = (): void => {
  uni.showToast({
    title: '关于系统功能开发中',
    icon: 'none'
  })
}

const logout = (): void => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除本地存储的登录信息
        try {
          uni.removeStorageSync('token')
          uni.removeStorageSync('userInfo')
        } catch (e) {
          console.error('清除存储失败:', e)
        }
        
        uni.redirectTo({
          url: '/pages/index/index'
        })
      }
    }
  })
}

// 页面加载
onMounted(async () => {
  console.log('管理员设置页面加载完成')
  getStatusBarHeight()
  
  // 初始化数据
  await fetchAdminInfo()
  updateAdminStats()
})
</script>

<style>
.admin-profile-container {
  padding-bottom: 120rpx;
  background-color: #F5F5F5;
  min-height: 100vh;
}

.profile-header {
  background: linear-gradient(135deg, #FF8C42 0%, #FFA726 100%);
  padding: 30rpx;
  border-radius: 0 0 40rpx 40rpx;
}

.admin-info {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-section {
  position: relative;
  margin-right: 30rpx;
}

.admin-avatar, .default-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.default-avatar {
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 48rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.camera-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: #FF8C42;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid #FFFFFF;
}

.admin-details {
  flex: 1;
  color: #FFFFFF;
}

.admin-name {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.admin-role {
  font-size: 28rpx;
  opacity: 0.9;
  display: block;
  margin-bottom: 8rpx;
}

.stats-section {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  padding: 30rpx 0;
}

.stat-item {
  text-align: center;
  color: #FFFFFF;
}

.stat-number {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  opacity: 0.9;
}

.management-section, .settings-section {
  margin: 30rpx;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.view-all {
  display: flex;
  align-items: center;
  color: #999999;
  font-size: 24rpx;
}

.function-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -15rpx;
}

.function-item {
  width: calc(33.33% - 30rpx);
  margin: 15rpx;
  text-align: center;
  padding: 30rpx 0;
}

.function-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #FFF0E0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20rpx;
}

.function-text {
  font-size: 24rpx;
  color: #666666;
}

.settings-list {
  border-radius: 16rpx;
  overflow: hidden;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-left {
  display: flex;
  align-items: center;
}

.setting-text {
  font-size: 28rpx;
  color: #333333;
  margin-left: 20rpx;
}

.logout-section {
  margin: 30rpx;
}

.logout-btn {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 30rpx;
  text-align: center;
  border: 2rpx solid #FF4444;
}

.logout-text {
  font-size: 28rpx;
  color: #FF4444;
  font-weight: bold;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.admin-list-modal, .create-admin-modal, .edit-profile-modal, .password-modal, .role-modal {
  width: 650rpx;
  max-height: 80vh;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 30rpx;
}

.search-input {
  width: 100%;
  height: 70rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 35rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.status-filter {
  display: flex;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  overflow: hidden;
}

.filter-item {
  flex: 1;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #666666;
  background-color: #F5F5F5;
  border-right: 1rpx solid #DDDDDD;
}

.filter-item:last-child {
  border-right: none;
}

.filter-item.active {
  background-color: #FF8C42;
  color: #FFFFFF;
}

.admin-list {
  margin-top: 20rpx;
}

.admin-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.admin-item:last-child {
  border-bottom: none;
}

.admin-item-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.admin-item-avatar, .admin-item-default-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 20rpx;
}

.admin-item-default-avatar {
  background-color: #F0F0F0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666666;
}

.admin-item-info {
  flex: 1;
}

.admin-item-name {
  font-size: 28rpx;
  color: #333333;
  display: block;
  margin-bottom: 6rpx;
}

.admin-item-time, .admin-item-update {
  font-size: 22rpx;
  color: #999999;
  display: block;
  margin-bottom: 4rpx;
}

.admin-item-actions {
  display: flex;
  align-items: center;
}

.status-toggle {
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  margin-right: 20rpx;
  background-color: #F0F0F0;
  color: #666666;
}

.status-toggle.active {
  background-color: #E8F5E8;
  color: #4CAF50;
}

.role-btn {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #FFF0E0;
  border-radius: 25rpx;
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #F0F0F0;
}

.page-btn {
  padding: 10rpx 20rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666666;
  margin: 0 20rpx;
}

.page-btn.disabled {
  opacity: 0.5;
  color: #CCCCCC;
}

.page-info {
  font-size: 24rpx;
  color: #666666;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx 0;
  color: #999999;
  font-size: 24rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.status-selector {
  display: flex;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  overflow: hidden;
}

.status-option {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666666;
  background-color: #F5F5F5;
  border-right: 1rpx solid #DDDDDD;
}

.status-option:last-child {
  border-right: none;
}

.status-option.active {
  background-color: #FF8C42;
  color: #FFFFFF;
}

.role-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.role-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.role-item:last-child {
  border-bottom: none;
}

.role-checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #DDDDDD;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  background-color: #FFFFFF;
}

.role-checkbox.checked {
  background-color: #FF8C42;
  border-color: #FF8C42;
}

.role-info {
  flex: 1;
}

.role-name {
  font-size: 28rpx;
  color: #333333;
  display: block;
  margin-bottom: 6rpx;
}

.role-description {
  font-size: 24rpx;
  color: #666666;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  border-top: 1rpx solid #F0F0F0;
}

.cancel-btn, .confirm-btn {
  padding: 20rpx 40rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  text-align: center;
  flex: 1;
  margin: 0 10rpx;
}

.cancel-btn {
  background-color: #F0F0F0;
  color: #666666;
}

.confirm-btn {
  background-color: #FF8C42;
  color: #FFFFFF;
}
</style>
